<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="4.js" defer></script>
    <title>表单密码验证</title>
  </head>
  <body>
    <form action="">
      输入密码：<input type="text" name="password" />
      <span id="password-error"></span>
      <br />
      确认密码：<input type="text" name="confirmPassword" />
      <br />
      <button>提交</button>
    </form>
    <script>
      // 获取元素方法
      function query(name) {
        return document.querySelector(name)
      }

      //   键盘监听事件
      //   let i = 1
      //   query(`[name='password']`).addEventListener('keyup', function () {
      //     console.log(i)
      //   })

      confirm_password(`password`, `confirmPassword`, `两次密码不一样`, `#password-error`, `keyup`)
      //校验元素
      function confirm_password(password, confirmPassword, message, errorEl, eventType) {
        let elements = document.querySelectorAll(`[name='${password}']`, `[name='${confirmPassword}']`)

        elements.forEach(function (elem) {
          this.addEventListener(eventType, function () {
            const passwordValue = query(`[name='${password}']`).value
            const confirmPasswordValue = query(`[name='${confirmPassword}']`).value
            if (passwordValue != confirmPasswordValue) {
              query(`${errorEl}`).innerHTML = message
            } else {
              query(errorEl).innerHTML = ''
            }
          })
        })
      }
    </script>
  </body>
</html>
